import axiosInstance from "../plugins/axios";
import { ElMessage } from 'element-plus';
import { useTokenStore } from "../stores/token.ts";
export const Userlogin = async (username: string, password: string) => {
  const res = await axiosInstance.post("/auth/login", {
    username,
    password
  });
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    const tokenStore=useTokenStore()
    tokenStore.removeToken()
    ElMessage.error(res.data.message || "登录失败");
    throw new Error(res.data.message || "登录失败");
  }
}

export const Userlogout = async () => {
  const res = await axiosInstance.post("/auth/logout");
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "退出登录失败");
    throw new Error(res.data.message || "退出登录失败");
  }
}

export const getLoginInfo = async () => {
  const res = await axiosInstance.get("/auth/loginUser");
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取登录信息失败");
    throw new Error(res.data.message || "获取登录信息失败");
  }
}
export const getUserInfo = async (pageNum:number,pageSize:number) => {
  const res = await axiosInstance.post("/users/page", { pageNum, pageSize });
  if (res.data.code == 1) {
    return res.data.data; // 返回数据
  } else {
    ElMessage.error(res.data.message || "获取用户信息失败");
    throw new Error(res.data.message ||"获取用户信息失败");
  }
};
export const exportUserInfo = async () => {
  axiosInstance
    .get("/users/export", {
      responseType: "blob", // 重要
    })
    .then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      const contentDisposition = response.headers["content-disposition"];
      let fileName = "下载文件.xlsx";
      if (contentDisposition) {
        const fileNameMatch = contentDisposition.match(
          /filename\*=UTF-8''(.+)/
        );
        if (fileNameMatch.length === 2) {
          fileName = decodeURIComponent(fileNameMatch[1]);
        }
      }
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
    })
    .catch((error) => {
      console.error("下载失败:", error);
    });
};

export const importUserInfo = async (formData: FormData) => {
  const res = await axiosInstance.post("/users/import", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    throw new Error(res.data.message || "导入用户信息失败");
  }
}

export const searchUserInfo = async (pageNum:number,pageSize:number,search:any) => {
  const res = await axiosInstance.post("/users/search", { pageNum, pageSize,search });
  if (res.data.code === 1) {
    return res.data.data; // 返回数据
  } else {
    throw new Error(res.data.message || "搜索用户信息失败");
  }
}
